<script setup lang="ts">
import { getConsultOrderPayUrl } from '@/services'
import { showLoadingToast, showToast } from 'vant'
import { ref } from 'vue'

const props = defineProps<{
  actualPayment: number
  beforeClose: () => void
  show: boolean
  orderId: string
  payCallback: string
}>()
const emit = defineEmits<{
  (e: 'update:show', value: boolean): void
}>()
// 支付方式
const paymentMethod = ref<0 | 1>()
// 点击立即支付
// 不能在这里写对象, 因为他是同步代码, 这个时候paymentMethod, orderId 都是没有数据的
// const paramsObj = ref({
//     paymentMethod: paymentMethod.value,
//     orderId: orderId.value,
//     payCallback: 'http://localhost:5173/room'
//   })
// 支付地址
const pay = async () => {
  if (paymentMethod.value === undefined) return showToast('请选择支付方式')
  // 加载中效果
  showLoadingToast('跳转支付')
  const res = await getConsultOrderPayUrl({
    paymentMethod: paymentMethod.value,
    orderId: props.orderId,
    // 根据打包命令, 来判断执行的命令
    payCallback: import.meta.env.VITE_APP_CALLBACK + props.payCallback
  })
  // payCallback: 'http://localhost:5173/room'

  // 跳转到支付宝页面(不能用页面的router 跳转 因为跳转的话还会有本地的地址)
  window.location.href = res.data.payUrl
}
</script>

<template>
  <!-- 
    :close-on-popstate="false" 是否在页面回退时自动关闭 我们修改成为false

    v-model:show="show"  因为这个事件会自动更改我的数据所以不能让他改, 需要让父组件来更改
  -->
  <van-action-sheet
    :before-close="beforeClose"
    :show="show"
    @update:show="emit('update:show', $event)"
    title="选择支付方式"
    :closeable="false"
    :close-on-popstate="false"
  >
    <div class="pay-type">
      <p class="amount">￥{{ actualPayment.toFixed(2) }}</p>
      <van-cell-group>
        <van-cell title="微信支付" @click="paymentMethod = 0">
          <template #icon><cp-icon name="consult-wechat" /></template>
          <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
        </van-cell>
        <van-cell title="支付宝支付" @click="paymentMethod = 1">
          <template #icon><cp-icon name="consult-alipay" /></template>
          <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
        </van-cell>
      </van-cell-group>
      <div class="btn">
        <van-button type="primary" round block @click="pay">立即支付</van-button>
      </div>
    </div>
  </van-action-sheet>
</template>

<style scoped lang="scss">
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
